﻿using Newtonsoft.Json.Linq;

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Utils.Weixin.Pay.Http
{
    static class HttpClientExtensions
    {
        public static async Task<R> ReadAsWxPayAsync<R>(this Task<HttpResponseMessage> taskHttpContent)
        {
            return await ReadAsWxPayAsync<R>(await taskHttpContent);
        }

        public static async Task<R> ReadAsWxPayAsync<R>(this HttpResponseMessage httpContent)
        {
            var token = (JObject)await httpContent.Content.ReadAsJTokenAsync();
            if (httpContent.IsSuccessStatusCode)
            {
                return token.ToObject<R>();
            }
            if (token.ContainsKey("message") && token.ContainsKey("code"))
            {
                throw Error.ThirdError(token["code"].ToString(), token["message"].ToString());
            }
            throw Error.SystemError("请求失败：请检查地址是否正确");
        }
    }
}
